"""
自定义表格组件
"""

from PyQt5.QtWidgets import (
    QTableWidget, QTableWidgetItem, QHeaderView, QAbstractItemView,
    QVBoxLayout, QHBoxLayout, QWidget, QLabel, QLineEdit, QPushButton,
    QComboBox, QCheckBox
)
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtGui import QFont, QColor

class TableWidget(QWidget):
    """自定义表格组件"""
    
    # 信号定义
    row_selected = pyqtSignal(int)
    cell_double_clicked = pyqtSignal(int, int)
    
    def __init__(self, headers=None, parent=None):
        super().__init__(parent)
        
        self.headers = headers or []
        self.setup_ui()
        self.setup_style()
        
        # 连接信号
        self.table.itemSelectionChanged.connect(self.on_selection_changed)
        self.table.cellDoubleClicked.connect(self.on_cell_double_clicked)
    
    def setup_ui(self):
        """设置用户界面"""
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(8)
        
        # 工具栏
        toolbar_layout = QHBoxLayout()
        
        # 搜索框
        self.search_edit = QLineEdit()
        self.search_edit.setPlaceholderText("🔍 搜索...")
        toolbar_layout.addWidget(QLabel("搜索:"))
        toolbar_layout.addWidget(self.search_edit)
        
        # 筛选器
        self.filter_combo = QComboBox()
        self.filter_combo.addItems(["全部", "已启用", "已禁用"])
        toolbar_layout.addWidget(QLabel("筛选:"))
        toolbar_layout.addWidget(self.filter_combo)
        
        # 刷新按钮
        self.refresh_btn = QPushButton("🔄 刷新")
        toolbar_layout.addWidget(self.refresh_btn)
        
        # 导出按钮
        self.export_btn = QPushButton("📤 导出")
        toolbar_layout.addWidget(self.export_btn)
        
        toolbar_layout.addStretch()
        
        layout.addLayout(toolbar_layout)
        
        # 表格
        self.table = QTableWidget()
        self.table.setAlternatingRowColors(True)
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table.setSelectionMode(QAbstractItemView.SingleSelection)
        
        # 设置表头
        if self.headers:
            self.table.setColumnCount(len(self.headers))
            self.table.setHorizontalHeaderLabels(self.headers)
        
        # 设置表头样式
        header = self.table.horizontalHeader()
        header.setSectionResizeMode(QHeaderView.Interactive)
        header.setStretchLastSection(True)
        
        # 设置行高
        self.table.verticalHeader().setDefaultSectionSize(30)
        self.table.verticalHeader().setVisible(False)
        
        layout.addWidget(self.table)
        
        # 状态栏
        status_layout = QHBoxLayout()
        
        self.status_label = QLabel("共 0 条记录")
        status_layout.addWidget(self.status_label)
        
        status_layout.addStretch()
        
        # 分页控件
        self.page_combo = QComboBox()
        self.page_combo.addItems(["10", "20", "50", "100"])
        self.page_combo.setCurrentText("20")
        status_layout.addWidget(QLabel("每页显示:"))
        status_layout.addWidget(self.page_combo)
        
        layout.addLayout(status_layout)
    
    def setup_style(self):
        """设置样式"""
        self.setStyleSheet("""
            QTableWidget {
                background-color: #ffffff;
                border: 1px solid #e0e0e0;
                border-radius: 4px;
                gridline-color: #f0f0f0;
                selection-background-color: #e3f2fd;
            }
            QTableWidget::item {
                padding: 8px;
                border-bottom: 1px solid #f0f0f0;
            }
            QTableWidget::item:selected {
                background-color: #e3f2fd;
                color: #1976d2;
            }
            QTableWidget::item:hover {
                background-color: #f5f5f5;
            }
            QHeaderView::section {
                background-color: #f8f9fa;
                padding: 8px;
                border: none;
                border-right: 1px solid #e0e0e0;
                border-bottom: 2px solid #1976d2;
                font-weight: bold;
                color: #333333;
            }
            QLineEdit {
                padding: 6px 12px;
                border: 1px solid #e0e0e0;
                border-radius: 4px;
                background-color: #ffffff;
            }
            QLineEdit:focus {
                border-color: #1976d2;
            }
            QComboBox {
                padding: 6px 12px;
                border: 1px solid #e0e0e0;
                border-radius: 4px;
                background-color: #ffffff;
                min-width: 80px;
            }
            QPushButton {
                padding: 6px 12px;
                border: 1px solid #e0e0e0;
                border-radius: 4px;
                background-color: #ffffff;
            }
            QPushButton:hover {
                background-color: #f5f5f5;
            }
        """)
    
    def set_data(self, data):
        """设置表格数据"""
        if not data:
            self.table.setRowCount(0)
            self.status_label.setText("共 0 条记录")
            return
        
        self.table.setRowCount(len(data))
        self.table.setColumnCount(len(data[0]))
        
        # 设置表头
        if not self.headers and data:
            self.headers = [f"列{i+1}" for i in range(len(data[0]))]
            self.table.setHorizontalHeaderLabels(self.headers)
        
        # 填充数据
        for row, row_data in enumerate(data):
            for col, cell_data in enumerate(row_data):
                item = QTableWidgetItem(str(cell_data))
                item.setTextAlignment(Qt.AlignCenter)
                self.table.setItem(row, col, item)
        
        # 更新状态
        self.status_label.setText(f"共 {len(data)} 条记录")
        
        # 调整列宽
        self.table.resizeColumnsToContents()
    
    def get_selected_row(self):
        """获取选中的行"""
        current_row = self.table.currentRow()
        if current_row >= 0:
            row_data = []
            for col in range(self.table.columnCount()):
                item = self.table.item(current_row, col)
                row_data.append(item.text() if item else "")
            return row_data
        return None
    
    def on_selection_changed(self):
        """选择改变事件"""
        current_row = self.table.currentRow()
        if current_row >= 0:
            self.row_selected.emit(current_row)
    
    def on_cell_double_clicked(self, row, column):
        """单元格双击事件"""
        self.cell_double_clicked.emit(row, column)
    
    def clear(self):
        """清空表格"""
        self.table.setRowCount(0)
        self.status_label.setText("共 0 条记录")